package com.hue.gulimailcart.interceptor;

import com.hue.common.constant.AuthConstant;
import com.hue.common.constant.CartConstant;
import com.hue.common.to.UserInfoTo;
import com.hue.common.vo.UserVo;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author: 姚凤桥
 * @Date: 2021/12/12 21:02
 * @Description: 判断用户登录状态的拦截器
 */
public class LoginStatusInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        //获取当前登录的用户id
        UserVo loginUser = (UserVo) request.getSession().getAttribute(AuthConstant.LOGIN_USER);
        if (loginUser != null) {
            userInfoTo.setUserId(loginUser.getId());
        }

        //获取user-key
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (CartConstant.USER_KEY.equals(cookie.getName())) {
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setFlag(false);
                }
            }
        }

        //如果第一次使用购物车功能，还没有临时用户
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            userInfoTo.setUserKey(UUID.randomUUID().toString());
        }

        //使用ThreadLocal来存储userInfoTo
        threadLocal.set(userInfoTo);

        return true;
    }

    /**
     * 在响应请求时，命令浏览器存储一个user-key
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
        UserInfoTo userInfoTo = threadLocal.get();
        if (userInfoTo.isFlag()) {
            Cookie userKey = new Cookie(CartConstant.USER_KEY, userInfoTo.getUserKey());
            userKey.setDomain("gulimail.com");
            userKey.setMaxAge(CartConstant.USER_KEY_TIMEOUT);
            response.addCookie(userKey);
        }
    }
}
